package com.example.base.tools.tools;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;

import com.example.base.tools.config.PermissionException;

import java.util.List;

public class AppUtils {
    private static final boolean DEBUG = true;
    private static final String TAG = "SystemUtils";
    /**
     * 获取设备号
     *
     * @return
     */
    public static String getDeviceId(Context context) {
        return DeviceUUID.getDeviceUUID(context);
    }

    /**
     * 获取版本信息
     *
     * @return
     */
    public static String getVersionName(Context context) {
        try {
            String versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
            return versionName;
        } catch (PackageManager.NameNotFoundException e) {
            return "1.0";
        }
    }
    /**
     * 获取版本号
     *
     * @return
     */
    public static int getVersionCode(Context context) {
        try {
            int versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
            return versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            return 0;
        }
    }

    /**
     * 获取app名称
     *
     * @param context
     * @return
     */
    public static String getAppName(Context context) {
        try {
            ApplicationInfo applicationInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), 0);
            String name = (String) context.getPackageManager().getApplicationLabel(applicationInfo);
            return name;
        } catch (PackageManager.NameNotFoundException e) {
            return "";
        }
    }

    public static int px(float dipValue) {
        Resources r=Resources.getSystem();
        final float scale =r.getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    /**
     * 判断context指定的程序是否处于前台<br />
     * 注意:运行此方法需要<br />
     * &lt;uses-permission android:name="android.permission.GET_TASKS" /&gt;权限
     *
     * @param context
     * @return true:程序处于前台运行,false:Activity未处于前台状态
     */
    public static boolean isApplicationForeground(final Context context) throws PermissionException {
        return isApplicationForeground(context, context.getPackageName());
    }
    /**
     * 判断packageName指定的包名的程序是否处于前台<br />
     * 注意:运行此方法需要<br />
     * &lt;uses-permission android:name="android.permission.GET_TASKS" /&gt;权限
     *
     * @param context
     * @param packageName 要查询的包名
     * @return true:程序处于前台运行,false:Activity未处于前台状态
     */
    public static boolean isApplicationForeground(final Context context, String packageName)
            throws PermissionException {
        try {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
            if (!tasks.isEmpty()) {
                ComponentName topActivity = tasks.get(0).topActivity;
                if (topActivity.getPackageName().equals(packageName)) {
                    return true;
                }
            }
        } catch (SecurityException e) {
            Log.e(TAG, e.getMessage() + " Try to complete without permission");
            try {
                return isApplicationForegroundWithoutPermissions(context, packageName);
            } catch (UnsupportedOperationException e2) {
                throw new PermissionException(e);
            }
        }
        return false;
    }

    /**
     * 判断content给定的程序是否处于前台<br />
     * 注意:运行此方法不需要权限，但是比{@code isApplicationForeground}耗费更多时间
     *
     * @return true 在前台; false 在后台
     */
    public static boolean isApplicationForegroundWithoutPermissions(final Context context,
                                                                    final String packageName) throws UnsupportedOperationException {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        KeyguardManager km = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
        boolean isspecial = true;
        List<ActivityManager.RunningAppProcessInfo> appProcesses = am.getRunningAppProcesses();
        if (appProcesses == null) return false;
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(packageName)) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                        || appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
                    return true;
                }
                if (km.inKeyguardRestrictedInputMode()) return true;
            }
            if (isspecial) {
                /*
                 * http://blog.csdn.net/jw083411/article/details/7903038
                 * 经过测试，在一般情况下可行，在某些经过简洁版本的Android系统中
                 * RunningAppProcessInfo.importance的值一直为400，原因未找到，RunningAppProcessInfo
                 * 里面的变量importance其实是表示这个app进程的重要性，因为系统回收时候，会根据importance
                 * 的重要来杀进程的。具体可以去看文档。
                 */
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_BACKGROUND) {
                    isspecial = false;
                }
            }
        }
        if (isspecial) {
            Log.e(TAG,
                    "Utils.isApplicationForegroundWithoutPermissions():The system is unable to obtain accurate information and return false");
        }
        return false;
    }

    /**
     * 根据手机的分辨率从 dp 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
    public static int getWidth(Activity context) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.widthPixels;
    }

    public static int px2sp(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }

    public static int sp2px(Context context, float spValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (spValue * scale + 0.5f);
    }

    public static int getHeight(Activity context) {
        DisplayMetrics dm = new DisplayMetrics();
        context.getWindowManager().getDefaultDisplay().getMetrics(dm);
        return dm.heightPixels;
    }

    /**
     * 获取App安装包信息
     *
     * @return
     */
    public static PackageInfo getPackageInfo(Context context) {
        PackageInfo info = null;
        try {
            info = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace(System.err);
        }
        if (info == null)
            info = new PackageInfo();
        return info;
    }
    public static boolean isStorageExists() {
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            return true;
        }
        return false;
    }
    /*
     * 打开设置网络界面
     */
    public static void setNetworkMethod(final Context context) {
        // 提示对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setCancelable(false);
        try {
            builder.setTitle("网络设置提示")
                    .setMessage("网络连接不可用,是否进行设置?")
                    .setPositiveButton("设置",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    Intent intent = null;
                                    // 判断手机系统的版本 即API大于10 就是3.0或以上版本
                                    if (android.os.Build.VERSION.SDK_INT > 10) {
                                        intent = new Intent(
                                                android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                                    } else {
                                        intent = new Intent();
                                        ComponentName component = new ComponentName(
                                                "com.android.settings",
                                                "com.android.settings.WirelessSettings");
                                        intent.setComponent(component);
                                        intent.setAction("android.intent.action.VIEW");
                                    }
                                    context.startActivity(intent);
                                }
                            })
                    .setNegativeButton("取消",
                            new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog,
                                                    int which) {
                                    dialog.dismiss();
                                }
                            }).show();
        } catch (Exception e) {
        }

    }
    public static boolean isApkInDebug(Context context) {
        try {
            ApplicationInfo info = context.getApplicationInfo();
            return (info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
        } catch (Exception e) {
            return false;
        }
    }
}

